//  用户同时被两个部门录取时选择部门的页面
const baseUrl = 'https://gsdse.cn/api/KJRecruit';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //对应用户第一志愿
    departmentOne: "网络研发部",
    departmentOneChosen: false,
    //对应用户第二志愿
    departmentTwo: "秘书部",
    departmentTwoChosen: false,

    chosen: false,
    openid: "",
    userId: '',
  },
  //-------------------------------------------------------------------------------
  //methods


  //部门二选一
  chooseOne() {
    this.setData({
      departmentOneChosen: true,
      departmentTwoChosen: false,
      chosen: true
    })
  },

  chooseTwo() {
    this.setData({
      departmentOneChosen: false,
      departmentTwoChosen: true,
      chosen: true
    })
  },


  //确认选择按钮的方法-------------------------------------------------------------------------
  //如果用户没有对部门作出选择
  admissionUncertain() {
    wx.showToast({
      title: '请作出选择',
      icon: 'error'
    })
  },
  getNowDate() {
    var myDate = new Date();
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var hours = myDate.getHours(); //获取当前小时
    var minutes = myDate.getMinutes(); //获取当前分钟
    var seconds = myDate.getSeconds(); //获取当前秒
    var now = year + "/" + mon + "/" + date + " " + hours + ":" + minutes + ":" + seconds;
    return now;
  },
  //如果用户已经对部门做出了选择
  async admissionCertain() {
    //二重保险，再问一句是否确认选择
    wx.showModal({
      title: '是否确定你的选择?',
      content: '一旦确定无法更改',
      success: res => {
        if (res.confirm) {
          console.log('用户点击确定')
          this.handleSelect() //封装方法

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 似乎是因为await不能写在success里面，所以只能在外边再写一个函数了
  async handleSelect() {
    //存储用户信息
    const userInfo = await this.stroageUserInfo(this.data.userId)
    if (this.data.departmentOneChosen == true) { //用户选择了第一个部门
      //修改用户职位情况
      //获取的部门名称转化为部门ID
      const departmentIdOne = this.getDepartmentId(this.data.departmentOne)
      //通过录取信息更改所属部门
      await this.updateUser(userInfo.userId, departmentIdOne, userInfo)
      //还要把该用户的另一个志愿状态设置为不通过--->0
      //两个按钮 反选哪个部门 哪个部门的status由前端先变为1
      await this.updateUserWillingStatus(userInfo.applyId, "1", "0")
      //跳转到结果页面
      wx.navigateTo({
        url: '../admissionResult/admissionResult?userId=' + this.data.userId + '&departmentName=' + this.data.departmentOne + '&&passStatus=1'
      })
      return this.data.departmentOne
    } else { //用户选择了第二个部门，和上面同理
      //获取的部门名称转化为部门ID
      const departmentIdTwo = this.getDepartmentId(this.data.departmentTwo)
      //通过录取信息更改所属部门
      await this.updateUser(userInfo.userId, departmentIdTwo, userInfo)
      await this.updateUserWillingStatus(userInfo.applyId, "0", "1")

      //跳转到结果页面
      wx.navigateTo({
        url: '../admissionResult/admissionResult?userId=' + this.data.userId + '&departmentName=' + this.data.departmentTwo + '&&passStatus=2'
      })
      return this.data.departmentTwo
    }
  },

  //更改用户另一个志愿的状态，避免重复查询都可以继续反选
  updateUserWillingStatus(applyId, firstStatus, secondStatus) {
    wx.request({
      url: baseUrl + '/reverseWilling',
      method: 'POST',
      data: {
        applyId: applyId,
        firstStatus: firstStatus,
        secondStatus: secondStatus
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log("用户志愿状态已反转")
      }

    })
  },

  //获取用户的志愿信息
  selectUserWilling(userId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/SelectUserWilling',
        method: 'POST',
        data: {
          userId: userId
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          resolve({
            firstWilling: res.data.data.firstWilling,
            secondWilling: res.data.data.secondWilling
          })
        }
      })
    })
  },

  //存储用户信息
  stroageUserInfo(userId) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: baseUrl + '/selectUser',
        method: 'POST',
        data: {
          userId: userId
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          resolve(res.data.data)
        }
      })
    })
  },

  //通过departmentName反推departmentId
  getDepartmentId(departmentName) {
    var departmentArray = ["无", '秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部']
    for (let i = 1; i <= departmentArray.length; i++) {
      if (departmentName === departmentArray[i]) {
        return i
      }
    }
  },

  //志愿录取之后，修改用户的departmentId值
  updateUser(userId, departmentId, userInfo) {
    var that = this
    wx.request({
      url: baseUrl + '/updateUser',
      method: 'POST',
      data: {
        userId: userId,
        applyId: userInfo.applyId,
        phoneNumber: userInfo.phoneNumber,
        email: userInfo.email,
        positionName: 0,
        position: '干事',
        departmentId: departmentId,
        userName: userInfo.userName,
        schoolClass: userInfo.schoolClass,
        wxuserId: userInfo.wxuserId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        console.log('修改成功')
      }
    })
  },

  //---------------------------------------------------------------------------------
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(option) {
    var that = this
    //获取用户的志愿信息 
    const willing = await that.selectUserWilling(option.userId)
    const departmentArray = ['秘书处', '网络研发部', "影视部", '动画部', "PC技术部", "新媒体运营部", 'UI设计部']
    that.setData({
      departmentOne: departmentArray[willing.firstWilling - 1],
      departmentTwo: departmentArray[willing.secondWilling - 1],
      userId: option.userId,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})